<template>
    <Dialog :title="comInfo.name" :show="true" @close="cancel" :width="440" :height="360" :left="uiLeft" :top="uiTop">
        <div class="box">
            <div class="select-header">
                <el-button
                    @click="() => { selectTree.selectEvent.emit('select'), globalTreeType = '' }">重新框选</el-button>
                <el-button @click="deleteSelect">全部删除</el-button>
                <el-select style="width: 120px" v-model="globalTreeType" placeholder="请选择树种" clearable="true"
                    @change="changeTreeType" @clear="clearTreeType">
                    <el-option v-for=" item  in  treeModelClassesRef " :key="item.id" :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>
            </div>
            <div class="select-table">
                <el-table :data="currentTableData" style="width: 100%">
                    <el-table-column prop="id" label="ID" show-overflow-tooltip="true"> </el-table-column>
                    <el-table-column prop="treeTypeName" label="原始树种"> </el-table-column>
                    <el-table-column label="当前树种">
                        <template #default="scope">
                            <el-select style="width: 120px" v-model="treeTypeArr[scope.$index + (currentPage - 1) * 10]"
                                placeholder="当前树种" clearable="true"
                                @change="(val: any) => changeTreeType(val, scope.row.id)"
                                @clear="() => clearTreeType(scope.row.id)">
                                <el-option v-for=" item  in  treeModelClassesRef " :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select> </template>
                    </el-table-column>
                </el-table>
                <el-pagination layout="prev, pager, next,total" page-size="10" :total="treeData.total"
                    v-model:current-page=currentPage></el-pagination>
            </div>
        </div>
        <TooltipCom v-if="currentDialog == 'submit'" :content="'点击提交之后，会将所有正在选中的对象提交到服务端处理，请稍等。'" :title="'提交'"
            :isVisible="true" @close="currentDialog = undefined" @confirm="submitConfirm" />
    </Dialog>
</template>

<script setup lang="ts">
import Dialog from "@/components/Dialog.vue";
import { onMounted, ref, onBeforeUnmount, computed, watchEffect } from "vue";
import { getProjectManager } from "@/scripts/getProjectManager";
import { createVueDisposer, toVR } from "earthsdk-ui";
import TooltipCom from "@/components/common/TooltipCom.vue";
import { ElMessage } from "element-plus";
import { deleteTreeService } from "@/api";
const props = withDefaults(defineProps<{ comInfo: any }>(), {});
const emits = defineEmits(["cancel"]);
const cancel = () => {
    emits("cancel", props.comInfo.id);
};
const uiLeft = document.body.clientWidth - 10 - 430;
const uiTop = 60;

const d = createVueDisposer(onBeforeUnmount);
const objm = getProjectManager();
const selectTree = objm.eSForestManager.selectTree
const eSForest = objm.eSForestManager.eSForest;
const addTree = objm.eSForestManager.addTree;
const treeData = toVR<any>(d, [selectTree, "pages"])
// 删除
const currentDialog = ref<string | undefined>(undefined);
const deleteSelect = () => {
    if (treeData.value.data.length == 0) {
        ElMessage.error('请先框选树木');
        return;
    }
    currentDialog.value = 'submit';
}
// 提交 确定按钮
const submitConfirm = async () => {
    try {
        const param = {
            "plotId": objm.eSForestManager.esForestPlotId,
            "ids": treeData.value.data.map((item: any) => item.id),
        }
        const res = await deleteTreeService(param)
        // @ts-ignore
        if (res.status != 'ok') return;
        ElMessage({
            message: `删除成功`,
            type: 'success',
        })
        selectTree.deleteSelect.emit();
        objm.eSForestManager.refresh()
    } catch (error) {
        ElMessage({
            message: `删除失败，${error}`,
            type: 'error',
        })
        console.error(error);
    } finally {
        currentDialog.value = undefined;
    }
}
//#region 分页
const currentPage = ref(1);
const currentTableData = computed(() => {
    const temp = treeData.value.data.slice((currentPage.value - 1) * 10, currentPage.value * 10);
    temp.forEach((item: any, index: number) => {
        item.treeTypeName = eSForest.treeTypesAll[item.treeTypeId].name.replace(/\d+$/, '');
        if (treeTypeArr.value[index + (currentPage.value - 1) * 10] == "")
            treeTypeArr.value[index + (currentPage.value - 1) * 10] = item.treeTypeName;
    })
    return temp;
});
//#endregion
// #region 树种更换
const globalTreeType = ref('');
const treeTypeArr = ref<string[]>([]);
watchEffect(() => {
    treeTypeArr.value = new Array(treeData.value.data.length).fill('');
});
const treeModelClassesRef = toVR<any>(d, [addTree, "treeModelClasses"])
const changeTreeType = (val: any, treeId?: string) => {
    if (treeId == undefined) {
        treeTypeArr.value = new Array(treeData.value.data.length).fill(val);
    }
    if (val) {
        selectTree.updateSelect.emit(val, treeId);
    }
}
const clearTreeType = (treeId?: string) => {
    selectTree.updateSelect.emit('', treeId);
}
//#endregion
onMounted(() => {
    selectTree.selectEvent.emit("select");
});

onBeforeUnmount(() => {
    selectTree.selectEvent.emit("none");
    selectTree.clear()
});

</script>

<style scoped>
.box {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.select-table {
    display: flex;
    flex-direction: column;
    height: 275px;
    width: 100%;
    justify-content: space-between;
}

.bottom {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.bottom-pag {
    display: flex;
    justify-content: center;
}

.fun {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>